package com.hz.onlineshop.viewModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hz.onlineshop.model.entity.CategoryEntity
import com.hz.onlineshop.model.entity.ItemsEntity
import com.hz.onlineshop.model.entity.SliderEntity
import com.hz.onlineshop.model.service.MainService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {
    private val mainService = MainService.instance()

    private val _banner = MutableStateFlow<List<SliderEntity>>(emptyList())
    val banners: StateFlow<List<SliderEntity>> = _banner

    private val _categories = MutableStateFlow<List<CategoryEntity>>(emptyList())
    val categories: StateFlow<List<CategoryEntity>> = _categories

    private val _recommend = MutableStateFlow<List<ItemsEntity>>(emptyList())
    val recommend: StateFlow<List<ItemsEntity>> = _recommend

    init {
        loadBanners()
        loadCategory()
        loadItems()
    }

    private fun loadBanners() {
        viewModelScope.launch {
            try {
                val res = mainService.getBanners()
                if (res.code == 200 && res.data != null) {
                    _banner.value = res.data
                }
            } catch (e: Exception) {
                // 处理异常
            }
        }
    }
    private fun loadCategory() {
        viewModelScope.launch {
            try {
                val res = mainService.getCategoryList()
                if (res.code == 200 && res.data != null) {
                    _categories.value = res.data
                }
            } catch (e: Exception) {
                // 处理异常
            }
        }
    }
     private fun loadItems() {
        viewModelScope.launch {
            try {
                val res = mainService.getItemsList()
                if (res.code == 200 && res.data != null) {
                    _recommend.value = res.data
                }
            } catch (e: Exception) {
                // 处理异常
            }
        }
    }
}
